package com.onenine.app.view;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onenine.app.R;
import com.onenine.app.event.NVoiceStopEvent;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.SoundPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * 带有播放动画的语音条
 *
 * @author fly
 */
public class NVoiceBar extends RelativeLayout {

    private AnimationDrawable mVoiceAnimation;
    private TextView mMsgTv, mLengthTv;
    private ImageView mVoiceIv;
    private MediaPlayer mMediaPlayer;
    private String mVoicePath;

    public NVoiceBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context)
                .inflate(R.layout.layout_barrage_voice_bar, this, true);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mMsgTv = findViewById(R.id.aurora_tv_msgitem_message);
        mVoiceIv = findViewById(R.id.aurora_iv_msgitem_voice_anim);
        mLengthTv = findViewById(R.id.aurora_tv_voice_length);
        mMsgTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(mVoicePath)) {
                    return;
                }
                EventBus.getDefault().post(new NVoiceStopEvent(mVoicePath));
                mVoiceAnimation = (AnimationDrawable) mVoiceIv.getDrawable();
                if (mMediaPlayer.isPlaying()) {
                    stopMediaPlayer();
                    stopPlayAnim();
                } else {
                    playAnimVoice();
                }
            }
        });
    }

    /**
     * 设置性别样式
     *
     * @param sex
     */
    public void setSexStyle(int sex, boolean isLeft) {
        mMsgTv.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(isLeft ? RoleResLoader.DynamicResName.IC_VOICE_LEFT_BAR_BG
                        : RoleResLoader.DynamicResName.IC_VOICE_RIGHT_BAR_BG, sex));
    }

    /**
     * 设置微小模式
     */
    public void setSmallStyle() {
        float radio = 2.0f / 3;
        RelativeLayout.LayoutParams lp = (LayoutParams) mMsgTv.getLayoutParams();
        Drawable bg = mMsgTv.getBackground();
        lp.width = (int) (bg.getIntrinsicWidth() * radio);
        lp.height = (int) (bg.getIntrinsicHeight() * radio);
        mMsgTv.setLayoutParams(lp);
        RelativeLayout.LayoutParams lpp = (LayoutParams) mVoiceIv.getLayoutParams();
        Drawable vd = mVoiceIv.getDrawable();
        lpp.width = (int) (vd.getIntrinsicWidth() * radio);
        lpp.height = (int) (vd.getIntrinsicHeight() * radio);
        mVoiceIv.setLayoutParams(lpp);
    }

    /**
     * 播放动画音频
     */
    private void playAnimVoice() {
        FileInputStream fileInputStream = null;
        try {
            SoundPlayer.setAudioPlayByEarPhone(0);
            mMediaPlayer.reset();
            if (!mVoicePath.startsWith("http")) {
                fileInputStream = new FileInputStream(mVoicePath);
                mMediaPlayer.setDataSource(fileInputStream.getFD());
            } else {
                mMediaPlayer.setDataSource(getContext(), Uri.parse(mVoicePath));
            }
            mMediaPlayer.prepare();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mVoiceAnimation.start();
                    mp.start();
                }
            });
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlayAnim();
                    mp.reset();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置数据
     *
     * @param voicePath
     * @param duration
     */
    public void setData(String voicePath, float duration) {
        mVoicePath = voicePath;
        String lengthStr = (int) duration + getContext().getString(R.string.aurora_symbol_second);
        int width = (int) (-0.04 * duration * duration + 4.526 * duration + 75.214);
        mMsgTv.setWidth((int) (width * getContext().getResources().getDisplayMetrics().density));
        mLengthTv.setText(lengthStr);
    }

    /**
     * 设置语音时长的可见性
     *
     * @param visible
     */
    public void setVoiceLengthVisible(boolean visible) {
        mLengthTv.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    /**
     * 停止播放资源
     */
    private void stopMediaPlayer() {
        try {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放播放资源
     */
    private void releaseMediaPlayer() {
        try {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        mMediaPlayer = null;
    }

    /**
     * 停止播放动画
     */
    private void stopPlayAnim() {
        if (mVoiceAnimation != null) {
            mVoiceAnimation.stop();
            mVoiceAnimation.selectDrawable(0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(NVoiceStopEvent event) {
        if (!TextUtils.equals(event.voiceUrl, mVoicePath)) {
            stopPlayAnim();
            stopMediaPlayer();
        }
    }

    /**
     * 绑定窗口
     */
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        EventBus.getDefault().register(this);
    }

    /**
     * 移除播放
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopPlayAnim();
        releaseMediaPlayer();
        EventBus.getDefault().unregister(this);
    }

}
